package com.xxxx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.server.mapper.AdminMapper;
import com.xxxx.server.mapper.AdminRoleMapper;
import com.xxxx.server.mapper.RoleMapper;
import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.Menu;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.pojo.Role;
import com.xxxx.server.service.IAdminRoleService;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.utils.AdminUtils;
import com.xxxx.server.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private AdminMapper adminMapper;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Value("${jwt.tokenHead}")
	private String tokenHead;


	/**
	 * 登录
	 *
     * @param username
     * @param password
     * @param code
     * @param request
     * @return
	 */
	@Override
	public RespBean login(String username, String password, String code, HttpServletRequest request) {

		String captcha = (String) request.getSession().getAttribute("captcha");
		if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
			return RespBean.error("验证码输入错误，请重新输入！");
		}
		//登录
		UserDetails userDetails = userDetailsService.loadUserByUsername(username);
		if (null== userDetails||!passwordEncoder.matches(password,userDetails.getPassword())){
			return RespBean.error("用户名或密码不正确");
		}
		if (!userDetails.isEnabled()){
			return RespBean.error("账户被禁用，请联系管理员");
		}
		//设置用户对象至SpringSecurity全局上下文，方便其他地方使用
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
				null, userDetails.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authenticationToken);
		//得到jwt
		String token = jwtTokenUtil.generatorToken(userDetails);
		Map<String, Object> tokenMap = new HashMap<>();
		tokenMap.put("tokenHead",tokenHead);
		tokenMap.put("token",token);
		return RespBean.success("登录成功",tokenMap);
	}

	/**
	 * 根据用户名获取用户对象
	 * @param username
	 * @return
	 */
	@Override
	public Admin getAdminByUserName(String username) {
		return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
	}

	/**
	 * 根据用户Id查询角色列表
	 * @param adminId
	 * @return
	 */
	@Override
	public List<Role> getRoles(Integer adminId) {
		return roleMapper.getRoles(adminId);
	}

	/**
	 * 搜索所有操作员
	 * @param keywords
	 * @return
	 */
	@Override
	public List<Admin> getAllAdmins(String keywords) {
		return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
	}

	/**
	 * 更新用户密码
	 * @param oldPass
	 * @param pass
	 * @param adminId
	 * @return
	 */
	@Override
	public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
		Admin admin = adminMapper.selectById(adminId);
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		if (encoder.matches(oldPass, admin.getPassword())) {
			String newPassword = encoder.encode(pass);
			admin.setPassword(newPassword);
			if (adminMapper.updateById(admin) == 1) {
				return RespBean.success("密码修改成功！");
			}
			return RespBean.error("密码修改失败！");
		}
		return RespBean.error("密码输入错误！");
	}


}
